package com.youdianstar.app.common.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;

import com.google.common.io.Files;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;

/**
 * File: FileUtil
 * Author: 82149 Create: 2021/10/25 16:20
 * Changes (from 2021/10/25)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 */
public class FileUtil {
    private static String signImage = "chargejoy";

    /**
     * 判断URL 链接是否图片文件
     * --通过网络请求的Content-Type头信息判断
     */
    public static boolean isImageUrl(String url) {
        if (url.endsWith("jpg") || url.endsWith("png"))
            return true;
        URLConnection connection = null;
        try {
            connection = new URL(url).openConnection();
            String contentType = connection.getContentType();
            return contentType.startsWith("image/");
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String InputStream2File(Context mContext, InputStream inputStream, String fileName) {
        try {
            //图片沙盒文件夹
            File PICTURES = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            if (PICTURES != null && !PICTURES.exists()) {
                PICTURES.mkdir();
            }
            File imageFile = new File(PICTURES + "/" + fileName);
            //通过流将图片写入文件
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            Files.write(buffer, imageFile);
//            try {
//                int delete = mContext.getContentResolver().delete(uri, null, null);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            return imageFile.getPath();
        } catch (Exception ignored) {
        }
        return null;
    }

    /**
     * 图片压缩并保存
     * @param fileName 自定义文件名
     */
    public static String compressUriToFile(Context mContext,Uri imageUri,String fileName){
        try {
            //图片沙盒文件夹
            File PICTURES = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            if (PICTURES != null && !PICTURES.exists()) {
                PICTURES.mkdir();
            }
            ByteArrayOutputStream compressSt = compressImage2Stream(mContext,imageUri,600*1024);
            File imageFile = saveBitmap(compressSt,PICTURES + "/" + fileName);
            return imageFile.getPath();
        }catch (Exception e){
            return "";
        }
    }

    /**
     * 图片压缩
     * @param targetSizeKb  200KB = 200 * 1024;
     */
    public static ByteArrayOutputStream compressImage2Stream(Context context, Uri imageUri, int targetSizeKb) {
        try {
            // 获取图片的原始大小
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageUri), null, options);

            // 计算压缩比例
            int width = options.outWidth;
            int height = options.outHeight;
            int inSampleSize = 1;
            while ((width / inSampleSize) > 1000 || (height / inSampleSize) > 1000) {
                inSampleSize *= 2;
            }

            // 重新读取图片，并进行压缩
            options.inSampleSize = inSampleSize;
            options.inJustDecodeBounds = false;
            Bitmap bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageUri), null, options);

            // 创建输出流，压缩图片
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            int quality = 100;
            int targetBytes = targetSizeKb * 1024;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);

            // 如果压缩后的大小大于指定大小，继续减小质量压缩
            while (outputStream.toByteArray().length > targetBytes && quality > 0) {
                outputStream.reset();
                quality -= 5;
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            }

            // 释放原始Bitmap资源
            bitmap.recycle();

            return outputStream;
        } catch (IOException e) {
            return null;
        }
    }


    /**
     * 将View加载成Bitmap -- 8.0+ 有问题
     *
     * @param v 可视View
     */
    private static Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        v.draw(c);
        return bmp;
    }

    /**
     * 将View 保存成图片 --保存到相册
     *
     * @param view 目标View
     */
    public static void saveViewToImage(Activity mContext, View view) {
        try {
            // 把一个View转换成图片
            Bitmap cacheBmp = loadBitmapFromView(view);
            saveBitmapToImage(mContext,cacheBmp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存字节数组为本地图片文件
     *
     * @param baos file stream
     * @param path file path
     */
    public static File saveBitmap(ByteArrayOutputStream baos, String path) {
        File file = new File(path);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception ignored) {
        }
        return file;
    }

    /**
     * Bitmap保存成图片 --保存到相册
     *
     * @param cacheBmp 目标图片
     */
    public static void saveBitmapToImage(Activity mContext, Bitmap cacheBmp) {
        if (null == cacheBmp){
            LogUtil.e("----Bitmap null");
            return;
        }
        try {
            String imageName = Calendar.getInstance().getTimeInMillis() + ".png";
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q){
                File imageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), signImage);
                if (!imageDir.exists())
                    imageDir.mkdir();
                File file = new File(imageDir, imageName);
                //LogUtil.d("----Bitmap save: "+file.getAbsolutePath());
                FileOutputStream fos = new FileOutputStream(file);
                cacheBmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            }else {
                //Android 11+
                final ContentValues values = new ContentValues();
                //Environment.DIRECTORY_SCREENSHOTS:截图,图库中显示的文件夹名。
                values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + signImage);
                values.put(MediaStore.MediaColumns.DISPLAY_NAME, imageName);
                values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
                values.put(MediaStore.MediaColumns.IS_PENDING, 1);

                ContentResolver resolver = mContext.getContentResolver();
                final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                try (OutputStream out = resolver.openOutputStream(uri)) {
                    if (!cacheBmp.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                        throw new IOException("Failed to compress");
                    }
                }
                values.clear();
                values.put(MediaStore.MediaColumns.IS_PENDING, 0);
                values.putNull(MediaStore.MediaColumns.DATE_EXPIRES);
                resolver.update(uri, values, null, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
